package hu.blok1.veilingsite.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class DBConnector extends RemoteServiceServlet {
	final static String LINK_STRING = "jdbc:oracle:thin:@ondora01.hu.nl:8521:cursus01";
	final static String USER_STRING = "THO5_2011_3B_TEAM4";
	final static String PASS_STRING = "THO5_2011_3B_TEAM4";
	private static Connection con = null;
	private static Statement stmt = null;
	private static ResultSet rs = null;

	public static void SendStatement(String query) {
		loadDriver();
		GetConnection();
		try {
			stmt = con.createStatement();
			int m = stmt.executeUpdate(query);
		} catch (SQLException se) {
			// Inform user of any SQL errors
			System.out.println("SQL Exception: " + se.getMessage());
			System.out.println("SQLState: " + se.getSQLState());
			System.out.println("ErrorCode: " + se.getErrorCode());
			se.printStackTrace(System.out);
		}
	}

	public static ResultSet GetResultSet(String query)
			throws IllegalArgumentException {
		loadDriver();
		GetConnection();
		try {
			stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = stmt.executeQuery(query);
		} catch (SQLException se) {
			System.out.println(se.getMessage());
		}
		return rs;
	}

	public static void CloseAll() {
		CloseRS();
		CloseStatement();
		CloseConnection();
	}

	public static void CloseConnection() {
		try {
			if (!con.isClosed() && con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void CloseStatement() {
		try {
			if (!stmt.isClosed() && stmt != null) {
				stmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void CloseRS() {
		try {
			if (!rs.isClosed() && rs != null) {
				rs.close();
			}
		} catch (SQLException e2) {
			e2.printStackTrace();
		}
	}

	private static void GetConnection() {
		try {
			con = DriverManager.getConnection(LINK_STRING, USER_STRING,
					PASS_STRING);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private static void loadDriver() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			System.out.println("Unable to load Driver Class");
		}
	}
}